package edu.dev.tfile.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.dev.tfile.common.Utils;

public class DownloadService extends HttpServlet {

	private static final long serialVersionUID = -4799760449438494905L;

	private static final String BASE_URI = "/browse";

	private static String basePath = Utils.getConfig("download_path");

	static {
		basePath = basePath.replace("\\", "/");
		if ("/".equals(basePath.substring(basePath.length() - 1))) {
			basePath = basePath.substring(0, basePath.length() - 1);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String appendUri = req.getRequestURI();
		appendUri = URLDecoder.decode(appendUri, "UTF-8");
		String path = "";
		if (BASE_URI.equals(appendUri)) {
			path = basePath;
		} else {
			path = basePath + appendUri.substring(BASE_URI.length());
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		File currentFile = new File(path);
		if (!currentFile.exists()) {
			Utils.sendMsg(resp, Utils.getJSON(list));
		} else if (currentFile.isDirectory()) {
			if (!"/".equals(appendUri.substring(appendUri.length() - 1))) {
				appendUri = appendUri + "/";
			}
			File[] files = currentFile.listFiles();
			for (File file : files) {
				list.add(getFileAttr(file, appendUri));
			}
			Utils.sendMsg(resp, Utils.getJSON(list));
		} else if (currentFile.isFile()) {
			String fileName = URLEncoder.encode(currentFile.getName(),"UTF-8");
			resp.setContentType("APPLICATION/OCTET-STREAM");
			resp.setHeader("Content-Disposition", "attachment;   filename=\""   +  fileName  +   "\"");   
			InputStream is = new FileInputStream(currentFile);
			OutputStream os = resp.getOutputStream();
			int byteread = 0;
			byte[] b = new byte[1024];
			while ((byteread = is.read(b)) != -1) {
				os.write(b, 0, byteread);
			}
			os.flush();
			is.close();
			os.close();
		}
	}

	private Map<String, Object> getFileAttr(File file, String uri) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", file.getName());
		map.put("path", uri + file.getName());
		if (file.isDirectory()) {
			map.put("size", "");
			map.put("dl", 0);
		} else {
			map.put("size", String.valueOf(file.length()));
			map.put("dl", 1);
		}
		return map;
	}

}
